/**
 * 
 */
package com.mbengue.corp.apr.ra.dao.impl;

import java.io.Serializable;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.mbengue.corp.apr.ra.core.Image;
import com.mbengue.corp.apr.ra.dao.ImageDao;
import com.mbengue.corp.apr.ra.util.HibernateUtil;

/**
 * @author MMB11447
 *
 */
public class ImageDaoImpl implements Serializable, ImageDao {
  private static final long serialVersionUID = 1L;
  private Session session;

  public ImageDaoImpl() {
    session = HibernateUtil.getSessionFactory();
  }

  /* (non-Javadoc)
   * @see com.mbengue.corp.apr.ra.dao.ImageDao#ajouterImage(com.mbengue.corp.apr.ra.core.Image)
   */
  @Override
  public void ajouterImage(Image image) throws HibernateException {
    Transaction transaction = session.beginTransaction();
    try {
      session.save(image);
      transaction.commit();
    } catch (Exception e) {
      transaction.rollback();
      throw new HibernateException(e);
    } finally {
      session.flush();
      //session.close();
    }
  }

  /* (non-Javadoc)
   * @see com.mbengue.corp.apr.ra.dao.ImageDao#modifierImage(com.mbengue.corp.apr.ra.core.Image)
   */
  @Override
  public void modifierImage(Image image) throws HibernateException {
    Transaction transaction = session.beginTransaction();
    try {
      session.update(image);
      transaction.commit();
    } catch (Exception e) {
      transaction.rollback();
      throw new HibernateException(e);
    } finally {
      session.flush();
      session.close();
    }
  }

  /* (non-Javadoc)
   * @see com.mbengue.corp.apr.ra.dao.ImageDao#trouverImage(java.lang.String)
   */
  @Override
  public Image trouverImage(String nom) throws HibernateException {
    Criteria criteria = session.createCriteria(Image.class);
    criteria.add(Restrictions.idEq(nom));
    return (Image) criteria.uniqueResult();
  }

  /* (non-Javadoc)
   * @see com.mbengue.corp.apr.ra.dao.ImageDao#supprimerImage(java.lang.String)
   */
  @Override
  public void supprimerImage(String nom) throws HibernateException {
    Image image = trouverImage(nom);
    if (image == null) {
      return;
    }
    Transaction transaction = session.beginTransaction();
    try {
      session.delete(image);
      transaction.commit();
    } catch (Exception e) {
      transaction.rollback();
      throw new HibernateException(e);
    } finally {
      session.flush();
      //session.close();
    }
  }
}
